package com.crud.project.controller;

import com.crud.project.po.Course;
import com.crud.project.service.CourseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CourseController {
    @Autowired
    private CourseService courseService;
    @GetMapping("/course")
    public String course(@RequestParam(required=true,defaultValue="1") Integer page, Model model){
        PageHelper.startPage(page,3);
        List<Course> courseList=courseService.findAllCourse();
        PageInfo<Course> pageInfo=new PageInfo<>(courseList);
        model.addAttribute("course",pageInfo);
        return "course";
    }

    @GetMapping("/course-input")
    public String roleinput(Model model, HttpSession httpSession){
        if (httpSession.getAttribute("course")==null){
            Course course=new Course();
            model.addAttribute("course",course);
        }
        return "course-input";
    }

    @GetMapping("/updateCourse-input/{id}")
    public String updateInput(@PathVariable Long id, Model model){
        Course course=courseService.findCourceByCourseId(id);
        model.addAttribute("course",course);
        return "course-input";
    }

    @PostMapping("/updateCourse/{id}")
    public String updateRole(@PathVariable Long id,Course course,Model model){
        Course course1=courseService.findCourceByCourseId(id);
        course.setCourse_id(course1.getCourse_id());
        course.setCourse_create_time(new Date());
        BeanUtils.copyProperties(course,course1);
        courseService.updateCourse(course1);
        return "redirect:/course";
    }

    @PostMapping("/insertCourse")
    public String insertRole(Course course){
        course.setCourse_create_time(new Date());
        courseService.insertCourse(course);
        return "redirect:/course";
    }

    @GetMapping("/deleteCourse/{id}")
    public String deleteCourse(@PathVariable Long id){
        courseService.deleteCourseById(id);
        return "redirect:/course";
    }
}
